package com.bcsq.todolistdemo.camera;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bcsq.todolistdemo.BaseActivity;
import com.bcsq.todolistdemo.R;
import com.bcsq.todolistdemo.util.HttpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

/**
 * 相机拍照
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CameraActivity extends BaseActivity implements View.OnClickListener  {
    private static final String TAG = "CameraActivity";
    private String[] permission = {Manifest.permission.CAMERA};
    private TextureView mTextureView;
    private HandlerThread mCameraThread;
    private Handler mCameraHandler;
    private Size mPreviewSize;
    private Size mCaptureSize;
    private String mCameraId;
    private Context mContext;
    CaptureRequest.Builder mCaptureRequestBuilder;
    ImageReader mImageReader ;
    CameraCaptureSession mCameraCaptureSession;
    CaptureRequest mCaptureRequest;
    private CameraDevice mCameraDevice;
    Uri outputFileUri = null;
    File file;
    String fileName = "";
    //图片数据
    byte [] data;

    ImageView btnCapture;

    private int screenWidth = 480;
    private int screenHeight = 800;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏无状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_camera);

        init();
    }

    private void init() {
        mContext = this;
        mTextureView = findViewById(R.id.camera_preview_view);
        btnCapture = findViewById(R.id.btn_capture);

        btnCapture.setOnClickListener(this);

        DisplayMetrics  dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
    }


    //设置监听SurefaceTexture的事件
    @Override
    protected void onResume() {
        super.onResume();
        startCameraThread();
        if (!mTextureView.isAvailable()) {
            mTextureView.setSurfaceTextureListener(mTextureListener);
        } else {
            startPreview();
        }
    }

    @Override
    protected void onPause() {
        closeCamera();
        super.onPause();
    }

    //    在新线程CameraThread中创建Handler对camera的消息进行排队处理，包括拍照数据保存
    private void startCameraThread() {
        mCameraThread = new HandlerThread("CameraThread");
        mCameraThread.start();
        mCameraHandler = new Handler(mCameraThread.getLooper());
    }

    //    当SurefaceTexture准备好后会回调SurfaceTextureListener 的onSurfaceTextureAvailable()方法
    private TextureView.SurfaceTextureListener mTextureListener = new TextureView.SurfaceTextureListener() {

        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            setupCamera(width, height);
            try {
                openCamera();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surfaceTexture, int i, int i1) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surfaceTexture) {

        }
    };


    /**
     * 2、为了更好地预览，我们根据TextureView的尺寸设置预览尺寸，Camera2中使用CameraManager来管理摄像头
     * @param width
     * @param height
     */
    private void setupCamera(int width, int height) {
        //获取摄像头的管理者CameraManager
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            //遍历所有摄像头
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);//lens_facing
                //此处默认打开后置摄像头
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT)
                    continue;
                //获取StreamConfigurationMap，它是管理摄像头支持的所有输出格式和尺寸
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                assert map != null;
                //根据TextureView的尺寸设置预览尺寸
                mPreviewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height);
                //获取相机支持的最大拍照尺寸
                mCaptureSize = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new Comparator<Size>() {
                    @Override
                    public int compare(Size lhs, Size rhs) {
                        return Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getHeight() * rhs.getWidth());
                    }
                });
                //此ImageReader用于拍照所需
//                setupImageReader();
                mCameraId = cameraId;
                break;
            }
        } catch (Exception e) {
                e.printStackTrace();
        }
    }

    //选择sizeMap中大于并且最接近width和height的size
    private Size getOptimalSize(Size[] sizeMap, int width, int height) {
        List<Size> sizeList = new ArrayList<>();
        for (Size option : sizeMap) {
            if (width > height) {
                if (option.getWidth() > width && option.getHeight() > height) {
                    sizeList.add(option);
                }
            } else {
                if (option.getWidth() > height && option.getHeight() > width) {
                    sizeList.add(option);
                }
            }
        }
        if (sizeList.size() > 0) {
            return Collections.min(sizeList, new Comparator<Size>() {
                @Override
                public int compare(Size lhs, Size rhs) {
                    return Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getWidth() * rhs.getHeight());
                }
            });
        }
        return sizeMap[0];
    }


    /**
     *  开启相机
     * @throws CameraAccessException
     */
    private void openCamera() throws CameraAccessException {
        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) mContext, permission, 1);
        }
        //打开相机，第一个参数指示打开哪个摄像头，第二个参数stateCallback为相机的状态回调接口，
        // 第三个参数用来确定Callback在哪个线程执行，为null的话就在当前线程执行
        manager.openCamera(mCameraId, mStateCallback, mCameraHandler);
    }

    /**
     * 实现StateCallback 接口，当相机打开后会回调onOpened方法，在这个方法里面开启预览
     */
    private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback(){
        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            System.out.println("onOpened");
            mCameraDevice = cameraDevice;//保存相机设备
            //开启预览
            startPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            System.out.println("onDisconnected");
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int i) {
            System.out.println("onError");
            cameraDevice.close();
            mCameraDevice = null;
        }
    };


    /**
     * 4、开启相机预览
     * 我们使用TextureView显示相机预览数据，Camera2的预览和拍照数据都是使用CameraCaptureSession会话来请求的
     */
    private void startPreview() {
        setupImageReader();
        SurfaceTexture mSurfaceTexture = mTextureView.getSurfaceTexture();
        //设置TextureView的缓冲区大小
        mSurfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Surface previewSurface = new Surface(mSurfaceTexture);//通过view创建surface对象
        try{
             mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            //绑定请求和surface
            mCaptureRequestBuilder.addTarget(previewSurface);

            /*创建相机捕获会话，第一个参数是捕获数据的输出Surface列表，
            第二个参数是CameraCaptureSession的状态回调接口，当它创建好后会回调onConfigured方法，
            第三个参数用来确定Callback在哪个线程执行，为null的话就在当前线程执行*/
            mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    try {
                        mCaptureRequest = mCaptureRequestBuilder.build();
                        mCameraCaptureSession = cameraCaptureSession;
                        /*设置预览是连续捕获图片*/
                        mCameraCaptureSession.setRepeatingRequest(mCaptureRequest, null, mCameraHandler);

                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {

                }
            },mCameraHandler);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Camera2没有提供Camera中的PreviewCallback，那么我们如何实现预览帧数据呢？在Camera2中提供了CameraCaptureSession.CaptureCallback
     */
    private CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {

        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {

        }
    };


    /**
     * 6、实现拍照操作
     * Camera2拍照是通过ImageReader来实现的，首先先做些准备工作，比如设置拍照参数，如方向、尺寸等
     */
    private static final SparseIntArray ORIENTATION = new SparseIntArray();

    static {
         ORIENTATION.append(Surface.ROTATION_0, 90);
         ORIENTATION.append(Surface.ROTATION_90, 0);
         ORIENTATION.append(Surface.ROTATION_180, 270);
         ORIENTATION.append(Surface.ROTATION_270, 180);
    }


    /**
     * 现在准备工作做好了，还需要响应点击拍照事件，我们设置点击拍照按钮调用capture()方法，
     * 实现拍照：
     * @throws CameraAccessException
     */
    private void capturePicture() throws CameraAccessException {
        //首先我们创建请求拍照的CaptureRequest
        final CaptureRequest.Builder mCaptureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        //获取设备方向
        int rotation = getWindowManager().getDefaultDisplay().getRotation();

        mCaptureBuilder.addTarget(mImageReader.getSurface());

        //设置拍照方向orientation
        mCaptureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATION.get(rotation));
        /*停止取景*/
        mCameraCaptureSession.stopRepeating();
        /*  开始拍照，然后回调上面的接口重启预览，因为mCaptureBuilder设置ImageReader作为target，
        所以会自动回调ImageReader的onImageAvailable()方法保存图片 */
        mCameraCaptureSession.capture(mCaptureBuilder.build(), new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
                Log.i(TAG,"拍照");
                try {
                    /*设置自动对焦模式*/
                    unLockFocus();
//                    closeCamera();
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }, null);
    }

    /**
     * 设置自动对焦模式
     * @throws CameraAccessException
     */
    private void unLockFocus() throws CameraAccessException {
        /**
         * control_af_trigger
         * CONTROL_AF_MODE control_af_mode
         */
        mCaptureRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);

        mCameraCaptureSession.setRepeatingRequest(mCaptureRequest, null, mCameraHandler);
    }


    /**
     * 设置图片格式
     */

    private void setupImageReader() {
        //前三个参数分别是需要的尺寸和格式，最后一个参数代表每次最多获取几帧数据
        mImageReader = ImageReader.newInstance(mCaptureSize.getWidth(),
                mCaptureSize.getHeight(),
                ImageFormat.JPEG,
                1);

        //监听ImageReader的事件，当有图像流数据可用时会回调onImageAvailable方法，它的参数就是预览帧数据，可以对这帧数据进行处理
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            public void onImageAvailable(ImageReader reader) {
                Image image = reader.acquireLatestImage();
                if (image != null){
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    data = new byte[buffer.remaining()];
                    buffer.get(data);
                    //开启线程异步保存图片 将图片保存到本地相册
                    mCameraHandler.post(new ImageSaver ());
//                    reader.close();
                    //将图片保存到服务器
                    mCameraHandler.post(new imageSaveServer());
                    reader.close();
                }
            }
        }, mCameraHandler);

    }


    /**
     * 保存到服务器
     */
    private class imageSaveServer implements Runnable{
        private Image mImage;
        private Bitmap bitmap;
        ByteBuffer buffer;

        public imageSaveServer() {}
        @Override
        public void run() {
            HttpUtil.post(data,  screenWidth,  screenHeight, fileName);
            Toast.makeText(mContext, "上传图片成功", Toast.LENGTH_SHORT).show();

        }
    }



    /**
     * 保存图片到本地
     */

    public class ImageSaver  implements Runnable {
        private Image mImage;

        public ImageSaver () { }

        @Override
        public void run() {
            //关闭image，释放资源，连续拍照
//            imageClose(mImage);
            fileName = Environment.getExternalStorageDirectory() + File.separator
                    + "DCIM" + File.separator + "Camera" + File.separator + "IMG_" + System.currentTimeMillis() + ".jpg";
            file = new File( fileName);
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                fout.write(data);
                fout.flush();
            } catch (Exception e) {
                e.printStackTrace();
                // 异常时删除保存失败的文件
                try {
                    if (file != null && file.exists() && file.isFile()) {
                        file.delete();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            } finally {
                if (fout != null) {
                    try {
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            outputFileUri = Uri.fromFile(file);
            Log.i("chen", String.valueOf(Uri.fromFile(file)));
        }
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_capture : //点击拍照
                try {
                    capturePicture();
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
                break;

        }

    }

    private void closeCamera() {
        if (null != mCameraCaptureSession) {
            mCameraCaptureSession.close();
            mCameraCaptureSession = null;
        }
        if (null != mCameraDevice) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
        if (null != mImageReader) {
            mImageReader.close();
            mImageReader = null;
        }
    }

    private void imageClose(Image image) {
        if (image != null)
            image.close();
    }


    //requestCode就是requestPermissions()的第三个参数
    //permission就是requestPermissions()的第二个参数
    //grantResults是结果，0调试通过，-1表示拒绝
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i("chen", String.valueOf(grantResults));
    }
}
